package com.zh.kotlin_mvvm.ui

import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.lifecycleScope
//import com.github.nkzawa.socketio.client.IO
//import com.github.nkzawa.socketio.client.Socket
import com.webrtc.OnlineUser
import com.webrtc.OnlineUserAdapter
import com.webrtc.WebRtcClient
import com.webrtc.jsonToList
import com.zh.common.base.BaseActivity
import com.zh.common.ktx.toJson
import com.zh.common.ktx.toast
import com.zh.common.socket.ClientSocket
import com.zh.common.socket.IReceiveMessage
import com.zh.kotlin_mvvm.databinding.ActivityWebRtcBinding
//import io.socket.client.IO
//import io.socket.client.Socket
import okio.ByteString
import org.json.JSONArray
import org.webrtc.EglBase
import org.webrtc.MediaStream

private const val REQUEST_CODE_PERMISSION = 100

/**
 * 参考地址: https://www.jianshu.com/p/34631a2ad612
 */
class WebRtcActivity : BaseActivity<ActivityWebRtcBinding>() {

    private val eglBase by lazy { EglBase.create() }
    private var webRtcClient: WebRtcClient? = null

//    private var socket: Socket?=null

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        ClientSocket.instance.close()
    }
    override fun initView(savedInstanceState: Bundle?) {
        viewBinding.hostButton.setOnClickListener {
            ClientSocket.instance.init(lifecycleScope, "ws://192.168.4.3:10098/websocket/1", object : IReceiveMessage{
                override fun onConnectSuccess() {
                    Log.d("WebSocket", "onConnectSuccess")
                    val json = toJson(hashMapOf(
                        "sid" to "1",
                        "message" to "hello websocket"
                    )) as String
                    ClientSocket.instance.sendMessage(json)
                }

                override fun onConnectFailed() {
                    Log.d("WebSocket", "onConnectFailed")
                }

                override fun onClose() {
                    Log.d("WebSocket", "onClose")
                }

                override fun onMessage(text: String?) {
                    Log.d("WebSocket", "onMessage: String = $text")
                }

                override fun onMessage(text: ByteString?) {
                    Log.d("WebSocket", "onMessage: Byte = $text")
                }

            })
//            saveHost2Sp(viewBinding.hostEditText.text.toString())
//            socket = IO.socket("http://signal.saas-xy.com:81/")
//            socket?.connect()
//            PermissionUtils.permission(
//                Manifest.permission.CAMERA,
//                Manifest.permission.RECORD_AUDIO
//            ).callback { isAllGranted, granted, deniedForever, denied ->
//                if (isAllGranted) {
//                    webRtcClient?.onDestroy()
//                    startWebRTC()
//                }
//            }.request()
//            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_CALENDAR)
//                != PackageManager.PERMISSION_GRANTED
//            ) {
//                ActivityCompat.requestPermissions(
//                    this,
//                    arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO),
//                    REQUEST_CODE_PERMISSION
//                )
//            } else {
//                webRtcClient?.onDestroy()
//                startWebRTC()
//            }
        }

        viewBinding.refreshIdsButton.setOnClickListener {
//            Log.d("isConnected", "${webRtcClient?.isConnected()}")
//            Log.d("isConnected", "${socket?.connected()}")
            Log.d("isConnected", "${ClientSocket.instance.isConnect()}")
            webRtcClient?.refreshIds()
        }
//
//        viewBinding.localRenderer.apply {
//            setEnableHardwareScaler(true)
//            init(eglBase.eglBaseContext, null)
//        }
//
//        viewBinding.remoteRenderer.apply {
//            setEnableHardwareScaler(true)
//            init(eglBase.eglBaseContext, null)
//        }
//        viewBinding.hostEditText.setText(getHostfromSp())
    }

    private fun startWebRTC() {
        webRtcClient = WebRtcClient(
            viewBinding.hostEditText.text.toString(),
            this.application,
            eglBase.eglBaseContext,
            object : WebRtcClient.RtcListener {
                override fun onOnlineIdsChanged(jsonArray: JSONArray) {
                    runOnUiThread {
                        "已刷新".toast()
                        Log.d("list", jsonArray.toString())
                        val list = jsonArray.toString().jsonToList<OnlineUser>() ?: listOf()
                        viewBinding.onlineUserRecyclerView.adapter =
                            OnlineUserAdapter(list) { webRtcClient?.callByClientId(it) }
                    }
                }

                override fun onCallReady(callId: String) {
                    runOnUiThread { "已连上服务器".toast() }
                    webRtcClient?.startLocalCamera(android.os.Build.MODEL, this@WebRtcActivity)
                }

                override fun onStatusChanged(newStatus: String) {
                    runOnUiThread { newStatus.toast() }
                }

                override fun onLocalStream(localStream: MediaStream) {
                    localStream.videoTracks[0].addSink(viewBinding.localRenderer)
                }

                override fun onAddRemoteStream(remoteStream: MediaStream, endPoint: Int) {
                    remoteStream.videoTracks[0].addSink(viewBinding.remoteRenderer)
                }

                override fun onRemoveRemoteStream(
                    localMS: MediaStream?, remoteMS: MediaStream?, endPoint: Int
                ) {
                    localMS?.let { it.videoTracks[0].removeSink(viewBinding.localRenderer) }
                    remoteMS?.let { it.videoTracks[0].removeSink(viewBinding.remoteRenderer) }
                }
            })
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_CODE_PERMISSION -> {
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                    startWebRTC()
                }
            }
        }
    }

    private fun saveHost2Sp(host: String) {
        val sharedPref = getPreferences(Context.MODE_PRIVATE)
        with(sharedPref.edit()) {
            putString("host", host)
            commit()
        }
    }

    private fun getHostfromSp(): String? {
        val sharedPref = getPreferences(Context.MODE_PRIVATE)
        return sharedPref.getString("host", "http://192.168.3.3:3479/")
    }

    override fun onPause() {
        super.onPause()
        webRtcClient?.onPause()
    }

    override fun onResume() {
        super.onResume()
        webRtcClient?.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        webRtcClient?.onDestroy()
        viewBinding.localRenderer.release()
        viewBinding.remoteRenderer.release()
    }
}